﻿/*
 * Created by SharpDevelop.
 * User: v.i.evgenyev
 * Date: 08.11.2011
 * Time: 17:27
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.IO;
using System.Windows.Forms;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using TinyCAT;
using System.Data.SQLite;
using System.Configuration;
using System.Drawing;

namespace TinyCAT
{
	/// <summary>
	/// Description of myAPP.
	/// </summary>
	public class myAPP
	{
// Text for translate
		public static class textToTranslate
		{
			public static string Value { get; set; }
		}
// Translated text		
		public static class TranslatedText
		{
			public static string Value { get; set; }
		}
//number of found variant
		public static class cntVar
		{
			public static int Value {get; set;}
		}
// installation values	
		public static class setting
		{
			public static string LangFrom {get; set;}
			public static string LangTo {get; set;}
			public static float Coincidence {get; set;}
			public static string tmdbName {get; set;}
			public static string fName {get; set;}
		}

//-----Levenshtein algorithm Алгоритм Левенштейна--------------------------

		public static int LevenshteinDistance(string string1,string string2)
		{
			if (string1==null) throw new ArgumentNullException("string1");
			if (string2==null) throw new ArgumentNullException("string2");
			int diff;					 
			int [,] m = new int[string1.Length+1,string2.Length+1];
			for (int i=0;i<=string1.Length;i++) m[i,0]=i;
			for (int j=0;j<=string2.Length;j++) m[0,j]=j;
			for (int i=1;i<=string1.Length;i++)
			for (int j=1;j<=string2.Length;j++)
			{
				diff=(string1[i-1]==string2[j-1])?0:1;
				m[i,j]=Math.Min(Math.Min(m[i-1,j]+1,
				m[i,j-1]+1),
				m[i-1,j-1]+diff);
			}
			return m[string1.Length,string2.Length];				
		}
//---------BING translation!-----------------------------------------------
		public static string BingTranslate (string input, string inputLang, string outputLang)
		{
			string translateUri = String.Format("http://api.microsofttranslator.com/V1/Http.svc/Translate?appId=D5153D8732AF28878A33E6FB8F943E806396DCEE&from={0}&to={1}",inputLang,outputLang);
			HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(translateUri);
			httpWebRequest.Proxy = WebRequest.GetSystemWebProxy();
			httpWebRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
// Request must be HTTP POST to include translation text 
			httpWebRequest.Method = "POST";
			httpWebRequest.ContentType = "text/plain";
			byte[] bytes = Encoding.UTF8.GetBytes(input);
			Stream os = null;
			try
			{
// Text is inserted into the body of the request 
				httpWebRequest.ContentLength = bytes.Length;
				os = httpWebRequest.GetRequestStream();
				os.Write(bytes, 0, bytes.Length);
			}
			finally
			{
// Close stream if successful 
				if (os != null)
				{
					os.Close();
				}
			}
			string output;
			try
			{
				WebResponse response = httpWebRequest.GetResponse();
				Stream stream = response.GetResponseStream();
				StreamReader reader = new StreamReader(stream);
				output = reader.ReadToEnd();
			}
			catch (Exception ex)
			{
// An error may be thrown if the request body is not recognisable as text 
// An error may be thrown if the from and to parameters are the same 
				output = "Error - " + ex.Message;
			}
			return output.ToString();
		}
//----------------Search in database------------------------------------------------
		public static string[] findTMDB(string input)
		{
			string[] variant = new string[100];
			try
			{
				SQLiteConnection cnn = new SQLiteConnection("Data Source = " + myAPP.setting.tmdbName);
				cnn.Open();
				SQLiteCommand SQLcommand = new SQLiteCommand(cnn);
				SQLiteParameter LMax = new SQLiteParameter("@LMax");
				SQLiteParameter LMin = new SQLiteParameter("@LMin");
				SQLiteParameter LFrom = new SQLiteParameter("@LFrom");
				SQLiteParameter LTo = new SQLiteParameter("@LTo");
				SQLcommand.CommandText = "SELECT FromTxt, ToTxt FROM Translate WHERE CNT BETWEEN @LMin AND @LMax AND FromLng = @LFrom AND ToLng = @LTo";
				SQLcommand.Parameters.Add(LMax);
				SQLcommand.Parameters.Add(LMin);
				SQLcommand.Parameters.Add(LFrom);
				SQLcommand.Parameters.Add(LTo);
				LMax.Value = Convert.ToInt32(input.Length*1.2);
				LMin.Value = Convert.ToInt32(input.Length*0.8);
				LFrom.Value = setting.LangFrom;
				LTo.Value = setting.LangTo;
				SQLiteDataReader res = SQLcommand.ExecuteReader ();
				cntVar.Value = 0;
				while (res.Read()==true)
				{
					string FromTxt = res.GetString(0);
					string ToTxt = res.GetString(1);
					float x = Convert.ToSingle(input.Length);
					float y = Convert.ToSingle(LevenshteinDistance(input,FromTxt));
					if ((x-y)/x > setting.Coincidence)  // вычисление совпадения фразы
					{
//valid variants with 1 to 100
//0 - variant BING!
						cntVar.Value = cntVar.Value + 1;
						variant[cntVar.Value] = ToTxt;
					}
				}
				if (cntVar.Value == 0)
				{
					variant [0] = BingTranslate(input,setting.LangFrom, setting.LangTo);
				}
				cnn.Close();
			}
			catch
			{
				MessageBox.Show("Database TM error.","TinyCAT",MessageBoxButtons.OK,MessageBoxIcon.Error);
			}
			return variant;
		}
//----------------read configuration from file-------------------------------
		public static void start_app_config ()
		{
			try
			{
				System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
				AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
				int X = Convert.ToInt32(config.AppSettings.Settings ["LocationX"].Value);
				int Y = Convert.ToInt32(config.AppSettings.Settings ["LocationY"].Value);
				int W = Convert.ToInt32(config.AppSettings.Settings ["SizeWidth"].Value);
				int H = Convert.ToInt32(config.AppSettings.Settings ["SizeHeight"].Value);
				MainForm.ActiveForm.Location = new Point (X, Y);
				MainForm.ActiveForm.Width = W;
				MainForm.ActiveForm.Height = H;
				setting.Coincidence = Convert.ToSingle (config.AppSettings.Settings ["Coincidence"].Value);
				setting.LangFrom = config.AppSettings.Settings ["LangFrom"].Value;
				setting.LangTo = config.AppSettings.Settings ["LangTo"].Value;
				myAPP.setting.tmdbName = config.AppSettings.Settings ["tmdbName"].Value;
			}
			catch
			{
			}
		}

//-------------Save the configuration file-------------------------------------------------------
		public static void  save_app_config ()
		{
			try
			{
				System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
				AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
				appSettings.Settings["LocationX"].Value = MainForm.ActiveForm.Location.X.ToString();
				appSettings.Settings["LocationY"].Value = MainForm.ActiveForm.Location.Y.ToString();
				appSettings.Settings["SizeWidth"].Value = MainForm.ActiveForm.Width.ToString();
				appSettings.Settings["SizeHeight"].Value = MainForm.ActiveForm.Height.ToString();
				appSettings.Settings["Coincidence"].Value = setting.Coincidence.ToString();
				appSettings.Settings["LangFrom"].Value = setting.LangFrom;
				appSettings.Settings ["LangTo"].Value = setting.LangTo;
				config.Save(); 
			}
			catch
			{
			}
		}
	}
}
